package com.mashibing.strategy.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author SNA
 * @date 2025/8/30
 * @Description 获取手机号归属地和运营商的工具类
 **/
@Component
public class MobileOperatorUtil {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    private final String url1 = "https://cx.shouji.360.cn/phonearea.php?number=";

    private final String CODE = "code";
    private final String DATA = "data";
    private final String PROVINCE = "province";
    private final String CITY = "city";
    private final String SP = "sp";
    private final String SPACE = " ";
    private final String SEPARATE = ",";

    public String getMobileInfoBy360(String mobile) {
        String url = url1;
        //1、发送请求获取信息
        String mobileInfoJSON = restTemplate.getForObject(url + mobile, String.class);

        // {"code":0,"data":{"province":"\u5e7f\u4e1c","city":"\u6e5b\u6c5f","sp":"\u79fb\u52a8"}}
        //2、解析json
        Map map = null;
        try {
            map = objectMapper.readValue(mobileInfoJSON, Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        Integer code  = (Integer) map.get(CODE);
        if (code != 0) {
            return null;
        }

        Map<String, String> areaAndOperator = (Map<String, String>) map.get(DATA);
        // 检查areaAndOperator是否为null
        if (areaAndOperator == null) {
            return null;
        }

        // 检查data中的值是否都是空字符串
        boolean allEmpty = true;
        for (Object value : areaAndOperator.values()) {
            if (value != null && !value.toString().trim().isEmpty()) {
                allEmpty = false;
                break;
            }
        }
        // 如果所有值都是空字符串，则返回null
        if (allEmpty) {
            return null;
        }

        String province = areaAndOperator.get(PROVINCE);
        String city = areaAndOperator.get(CITY);
        String sp =  areaAndOperator.get(SP);

        //3、封装为  省 市，运营商   的格式返回
        return province + SPACE + city + SEPARATE + sp;
    }
}
